package com.aifast.system.sys.dao;

import com.aifast.common.util.XmTree;
import com.aifast.system.sys.entity.SysOrg;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 机构表 Mapper 接口
 * </p>
 *
 * @author fujian
 * @since 2022-01-07
 */
@Mapper
public interface SysOrgDao extends BaseMapper<SysOrg> {

    @Select("SELECT GROUP_CONCAT(pid) from sys_org WHERE deleted = 0 and FIND_IN_SET(id,getParent(#{id})) order by sort desc")
    String getPids(@Param("id") Serializable id);

    @Select("SELECT id as value,name,state as `status`,pid,type from sys_org WHERE deleted is FALSE  ORDER BY sort desc")
    List<XmTree> selectData();

    @Select("SELECT * FROM sys_org WHERE deleted = 0 and FIND_IN_SET(#{orgId},pids) or id = #{orgId}")
    List<SysOrg> getChildren(Integer orgId);

    @Select("SELECT * FROM sys_org WHERE deleted = 0 and FIND_IN_SET(id,#{pids})")
    List<SysOrg> getParent(String pids);

    @Select("SELECT o.*,\n" +
            "(SELECT COUNT(u.id) FROM sys_user u WHERE u.deleted = 0 and org_id IN (SELECT id FROM sys_org WHERE id = o.id or FIND_IN_SET(o.id,pids))) as num\n" +
            "FROM sys_org o\n" +
            "WHERE o.deleted=0")
    List<SysOrg> selectAllListAndNum();
}
